<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-button icon="el-icon-plus" type="primary" @click="addDialogVisible = true" v-permission="permission.add">添加角色</el-button>
          <el-button icon="el-icon-edit" type="success" @click="editshowDilog(handleCheckboxRows[0].id)" v-permission="permission.edit" :disabled="handleCheckboxRows.length !== 1">修改</el-button>
          <el-button icon="el-icon-delete" type="danger" @click="deleteRoles" v-permission="permission.del" :disabled="handleCheckboxRows.length < 1">删除</el-button>
        </el-col>
        <el-col :span="4" style="text-align: right;float:right;">
          <table-tools
            :drawerSearch="drawerVisible"
            @searchchange="searchChange"
            @refreshclick="refreshClick">
          </table-tools>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-row :gutter="20">
        <el-col :span="16">
          <el-table
            highlight-current-row
            @current-change="handleCurrentChange"
            @selection-change="handleSelectionChange"
            v-loading="loading"
            :data="roleslist"
            ref="table"
            border
            stripe>
            <!-- 展开列 -->
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-row :class="['bdbottom', i1===0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                  <!-- 渲染一级权限 -->
                  <el-col :span="5">
                    <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.auth_name}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染二级和三级权限 -->
                  <el-col :span="19">
                    <!-- 通过for循环渲染二级权限 -->
                    <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                      <el-col :span="6">
                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.auth_name}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="18">
                        <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" :name="i3" closable @close="removeRightById(scope.row,item3.id)">{{item3.auth_name}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
               <!-- <pre>{{ scope.row }}</pre> -->
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="name" label="角色名称"></el-table-column>
            <el-table-column prop="description" label="角色描述"></el-table-column>
            <el-table-column label="操作" width="220px">
              <template v-slot="scope">
                <el-button plain type="primary" v-permission="permission.edit" icon="el-icon-edit" @click="editshowDilog(scope.row.id)">编辑</el-button>
                <!-- <el-button plain v-permission="permission.setting" type="warning" size="mini" icon="el-icon-setting" @click="settingRoleRulePower(scope.row)">分配权限</el-button> -->
                <el-button plain v-permission="permission.del" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card" style="margin-top: 15px;box-shadow: none !important;">
            <div slot="header" class="clearfix">
              <span>菜单设置</span>
              <el-button style="float: right;" v-permission="permission.setting" icon="el-icon-check" @click="allowRules" type="primary" :disabled="!showButton">保存</el-button>
            </div>
            <div class="el-dialog-div">
              <!-- 分配权限树形控件 -->
              <el-tree
                :data="rulesAllList"
                ref="TreeDom"
                node-key="id"
                :default-checked-keys="defRules"
                :default-expanded-keys="[1, 81, 48, 83]"
                :props="defaultProps"
                check-strictly
                accordion
                show-checkbox>
              </el-tree>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

  <!-- 添加角色对话框 -->
  <el-dialog
    title="添加角色"
    :visible.sync="addDialogVisible"
    width="580px"
    @close="addDilogClosed"
    :close-on-click-modal="false">
    <!-- 内容主体区域 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户组" prop="name">
        <el-input placeholder="请输入" v-model="addForm.name"></el-input>
      </el-form-item>
      <el-form-item label="用户组描述">
        <el-input placeholder="请输入" v-model="addForm.description"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addRole">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 编辑角色信息对话框 -->
  <el-dialog
    title="编辑角色信息"
    :visible.sync="editdialogVisible"
    width="580px"
    @close="editdialogClose"
    :close-on-click-modal="false">
    <el-form ref="editFormRef" :rules="editFormRules" :model="editForm" label-width="80px">
      <el-form-item label="用户组" label-width="120px">
        <el-input placeholder="请输入" v-model="editForm.name"></el-input>
      </el-form-item>
      <el-form-item label="用户组描述" label-width="120px">
        <el-input placeholder="请输入" v-model="editForm.description"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editdialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editRoleInfo">确 定</el-button>
    </span>
  </el-dialog>

  </div>
</template>

<script>
import tableTools from '@/components/tableToolsComponents' // tabs工具栏组件
import commonMethods from '@/utils/commonMethods.js'
export default {
  name: 'roles',
  mixins: [commonMethods],
  components: {
    tableTools
  },
  data () {
    return {
      // 指令权限
      permission: {
        add: ['admin', 'roles::add'],
        edit: ['admin', 'roles::edit'],
        del: ['admin', 'roles::delete'],
        setting: ['admin', 'roles::setting'], // 分配权限
        tagdel: ['admin', 'roles::tagdel']
      },
      handleCheckboxRows: [], // 多选存储rows
      drawerVisible: false, // 搜索栏显示状态
      loading: false, // 表格刷新loading状态
      showButton: false, // 菜单保存按钮状态
      // 角色列表
      roleslist: [],

      // 添加角色对象是否显示
      addDialogVisible: false,

      // 编辑角色dialog是否显示
      editdialogVisible: false,

      // 添加角色表单对象
      addForm: {},

      // 编辑角色表单对象
      editForm: {},

      // 添加角色表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },

      // 编辑角色表单的验证规则对象
      editFormRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },

      // 分配权限对话框dialog是否显示
      settingRuleVisible: false,

      // 栏目权限列表
      rulesAllList: [],

      // 树形控件默认配置
      defaultProps: {
        children: 'children',
        label: 'auth_name'
      },

      // 默认角色已分配选中栏目节点数组
      defRules: [],

      // 分配权限的角色Id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  mounted() {
    this.settingRoleRulePower() // 获取系统菜单列表
  },
  methods: {
    async getRolesList() {
      this.loading = true
      const { data: res } = await this.$http.get('roles')
      this.loading = false
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleslist = res.data
      // console.log(this.roleslist)
    },

    // 监听添加角色对话框的关闭事件
    addDilogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    // 编辑角色对话框的关闭事件
    editdialogClose() {
      this.$refs.editFormRef.resetFields()
    },

    // checkbox多选回调方法
    handleSelectionChange(val) {
      this.handleCheckboxRows = val
    },

    // 添加角色
    addRole() {
      // 表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 表示通过 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('roles', this.addForm)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.message)
        }
        this.$message.success('角色添加成功')
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getRolesList()
      })
    },

    // 显示编辑角色弹窗
    async editshowDilog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }

      this.editForm = res.data
      this.editdialogVisible = true
      console.log(res)
    },

    // 编辑角色确定事件
    editRoleInfo() {
      // 表单验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 表示通过 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('roles', this.editForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.message)
        }
        this.$message.success('修改成功')
        // 隐藏添加用户对话框
        this.editdialogVisible = false
        // 重新获取用户列表数据
        this.getRolesList()
      })
    },

    // 角色批量删除
    async deleteRoles() {
      const confirmresult = await this.$confirm('确定删除当前所选中角色吗? 此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('角色取消删除')
      }

      const idarr = []
      this.handleCheckboxRows.map(item => {
        idarr.push(item.id)
      })

      const { data: res } = await this.$http.post('delroles/', {
        idstr: idarr.join()
      })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.$message.success('角色删除成功')
      // 刷新数据列表
      this.getRolesList()
    },

    // 角色删除
    async deleteRole(id) {
      const confirmresult = await this.$confirm('确定删除当前角色吗? 此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmresult)
      if (confirmresult !== 'confirm') {
        return this.$message.info('角色取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.$message.success('角色删除成功')
      // 刷新数据列表
      this.getRolesList()
    },
    async removeRightById(role, ruleid) {
      const confirmresult = await this.$confirm('确定删除当前权限标签吗? 此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmresult !== 'confirm') {
        return this.$message.info('取消了删除')
      }

      const { data: res } = await this.$http.delete('roles/' + role.id + '/rule/' + ruleid)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }

      this.$message.success('删除成功')
      role.children = res.data
      // this.getRolesList()
    },

    // 列表单选回调
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中
        this.$refs.TreeDom.setCheckedKeys([])
        // 保存当前的角色id
        this.roleId = val.id
        // 初始化默认选中的key
        this.defRules = []
        val.ruleId.split(',').forEach(function(data) {
          _this.defRules.push(data)
        })
        this.showButton = true
      }
    },

    // 打开权限分配dialog
    async settingRoleRulePower() {
      const { data: res } = await this.$http.get('roles/rulesAlllist')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.rulesAllList = res.data
    },

    // 关闭权限分配dialog回调
    settingRuleClose() {
      this.defRules = []
    },
    // 角色权限设置
    async allowRules(role) {
      // console.log(this.$refs.TreeDom.getCheckedKeys())
      const keys = [
        ...this.$refs.TreeDom.getCheckedKeys(),
        ...this.$refs.TreeDom.getHalfCheckedKeys()
      ]
      const data = { ruleId: keys.join(',') }
      const { data: res } = await this.$http.post('roles/' + this.roleId + '/rules', data)

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.$notify.success('权限分配成功')
      this.settingRuleVisible = false
      this.update() // 无刷新更新
    },
    update() {
      // 列表无刷新更新
      this.$http.get('roles').then(res => {
        const roles = res.data.data.filter(item => {
          if (item.id === this.roleId) {
            return item
          }
        })
        for (let i = 0; i < this.roleslist.length; i++) {
          if (this.roleslist[i].id === roles[0].id) {
            this.roleslist[i] = roles[0]
          }
        }
      })
    },
    // 工具栏搜索按钮触发回调
    searchChange(val) {
      this.drawerVisible = val
    },
    // 工具栏刷新按钮触发回调
    refreshClick() {
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {margin:7px}

.bdtop {
  border-top:1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

.el-dialog-div {
  height: 60vh;
  overflow: auto;
}
</style>
